<?php

defined('SYSPATH') or die('Access error!');

class File
{

    /**
     * 转化 \ 为 /
     * 
     * @param	string	$path	路径
     * @return	string	路径
     */
    public static function change_path($path)
    {
        $path = str_replace('\\', '/', $path);
        if (substr($path, -1) != '/')
            $path = $path . '/';
        return $path;
    }

    /**
     * 创建目录
     * 
     * @param	string	$path	路径
     * @param	string	$mode	属性
     * @return	string	如果已经存在则返回true，否则为flase
     */
    public static function create_path($path, $mode = 0777)
    {
        if (is_dir($path))
            return TRUE;
        $path = self::change_path($path);
        $temp = explode('/', $path);
        $cur_dir = '';
        $max = count($temp);
        for ($i = 0; $i < $max; $i++)
        {
            $cur_dir .= $temp[$i] . '/';
            if (@is_dir($cur_dir))
                continue;
            @mkdir($cur_dir, 0777, true);
            @chmod($cur_dir, 0777);
        }
        return is_dir($path);
    }

    /**
     * iconv 编辑转换
     */
    public static function iconv($in_charset, $out_charset, $str)
    {
        $in_charset = strtoupper($in_charset);
        $out_charset = strtoupper($out_charset);
        if (function_exists('mb_convert_encoding'))
        {
            return mb_convert_encoding($str, $out_charset, $in_charset);
        }
        else
        {
            pc_base::load_sys_func('iconv');
            $in_charset = strtoupper($in_charset);
            $out_charset = strtoupper($out_charset);
            if ($in_charset == 'UTF-8' && ($out_charset == 'GBK' || $out_charset == 'GB2312'))
            {
                return utf8_to_gbk($str);
            }
            if (($in_charset == 'GBK' || $in_charset == 'GB2312') && $out_charset == 'UTF-8')
            {
                return gbk_to_utf8($str);
            }
            return $str;
        }
    }

    /**
     * 拷贝目录及下面所有文件
     * 
     * @param	string	$fromdir	原路径
     * @param	string	$todir		目标路径
     * @return	string	如果目标路径不存在则返回false，否则为true
     */
    public static function copy_file($fromdir, $todir)
    {

        $fromdir = self::change_path($fromdir);
        $todir = self::change_path($todir);

        if (!is_dir($fromdir))
            self::create_path($fromdir);



        if (!is_dir($todir))
        {

            self::create_path($todir);
        }
        $list = glob($fromdir . '*');

        if (!empty($list))
        {
            foreach ($list as $v)
            {
                $path = $todir . basename($v);
                if (is_dir($v))
                {
                    self::copy_file($v, $path);
                }
                else
                {
                    copy($v, $path);
                    @chmod($path, 0777);
                }
            }
            self::delete_file($fromdir);
        }
        else
        {
            self::delete_file($fromdir);
        }
        return TRUE;
    }

    /**
     * 转换目录下面的所有文件编码格式
     * 
     * @param	string	$in_charset		原字符集
     * @param	string	$out_charset	目标字符集
     * @param	string	$dir			目录地址
     * @param	string	$fileexts		转换的文件格式
     * @return	string	如果原字符集和目标字符集相同则返回false，否则为true
     */
    public static function change_charset($in_charset, $out_charset, $dir, $fileexts = 'php|html|htm|shtml|shtm|js|txt|xml')
    {
        if ($in_charset == $out_charset)
            return false;
        $list = self::list_file($dir);
        foreach ($list as $v)
        {
            if (pathinfo($v, PATHINFO_EXTENSION) == $fileexts && is_file($v))
            {
                file_put_contents($v, iconv($in_charset, $out_charset, file_get_contents($v)));
            }
        }
        return true;
    }

    /**
     * 列出目录下所有文件
     * 
     * @param	string	$path		路径
     * @param	string	$exts		扩展名
     * @param	array	$list		增加的文件列表
     * @return	array	所有满足条件的文件
     */
    public static function list_file($path, $exts = '', $list = array())
    {
        $path = self::change_path($path);
        $files = glob($path . '*');
        foreach ($files as $v)
        {
            if (!$exts || pathinfo($v, PATHINFO_EXTENSION) == $exts)
            {
                $list[] = $v;
                if (is_dir($v))
                {
                    $list = self::list_file($v, $exts, $list);
                }
            }
        }
        return $list;
    }

    /**
     * 目录列表
     * 
     * @param	string	$dir		路径
     * @param	int		$parentid	父id
     * @param	array	$dirs		传入的目录
     * @return	array	返回目录列表
     */
    public static function dir_tree($dir, $parentid = 0, $dirs = array())
    {
        global $id;
        if ($parentid == 0)
            $id = 0;
        $list = glob($dir . '*');
        foreach ($list as $v)
        {
            if (is_dir($v))
            {
                $id++;
                $dirs[$id] = array('id' => $id, 'parentid' => $parentid, 'name' => basename($v), 'dir' => $v . '/');
                $dirs = self::dir_tree($v . '/', $id, $dirs);
            }
        }
        return $dirs;
    }

    /**
     * 删除目录及目录下面的所有文件
     * 
     * @param	string	$dir		路径
     * @return	bool	如果成功则返回 TRUE，失败则返回 FALSE
     */
    public static function delete_files($dir)
    {
        $dir = self::change_path($dir);
        if (!is_dir($dir))
            return FALSE;
        $list = glob($dir . '*');
        foreach ($list as $v)
        {
            is_dir($v) ? self::delete_file($v) : @unlink($v);
        }
        return @rmdir($dir);
    }

    public static function delete_file($dir)
    {
        $dir_change = self::change_path($dir);
        $dir = rtrim($dir_change, '/');
        if (file_exists($dir))
        {
            @unlink($dir);
        }
    }

    //获取文件内容
    public static function readfile($filename)
    {
        $content = '';
        if (function_exists('file_get_contents'))
        {
            @$content = file_get_contents($filename);
        }
        else
        {
            if (@$fp = fopen($filename, 'r'))
            {
                @$content = fread($fp, filesize($filename));
                @fclose($fp);
            }
        }
        return $content;
    }

    //写入文件
    public static function writefile($filename, $writetext, $openmod = 'w')
    {
        if (@$fp = fopen($filename, $openmod))
        {
            flock($fp, 2);
            fwrite($fp, $writetext);
            fclose($fp);
            return true;
        }
        else
        {
            return false;
        }
    }

    /**
     * 文件下载
     * @param $filepath 文件路径
     * @param $filename 文件名称
     */
    public static function down_file($filepath, $filename = '')
    {
        if (!$filename)
            $filename = basename($filepath);
        if (self::is_ie())
            $filename = rawurlencode($filename);
        $filetype = self::get_ext($filename);
        $filesize = sprintf("%u", filesize($filepath));
        if (ob_get_length() !== false)
            @ob_end_clean();
        header('Pragma: public');
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT');
        header('Cache-Control: no-store, no-cache, must-revalidate');
        header('Cache-Control: pre-check=0, post-check=0, max-age=0');
        header('Content-Transfer-Encoding: binary');
        header('Content-Encoding: none');
        header('Content-type: ' . $filetype);
        header('Content-Disposition: attachment; filename="' . $filename . '"');
        header('Content-length: ' . $filesize);
        readfile($filepath);
        exit;
    }

    /**
     * IE浏览器判断
     * 
     */
    public static function is_ie()
    {
        $useragent = strtolower($_SERVER['HTTP_USER_AGENT']);
        if ((strpos($useragent, 'opera') !== false) || (strpos($useragent, 'konqueror') !== false))
            return false;
        if (strpos($useragent, 'msie ') !== false)
            return true;
        return false;
    }

    /**
     * 生成随机的数字串
     *
     * @author: weber liu
     * @return string
     */
    function random_filename()
    {
        $str = '';
        for ($i = 0; $i < 9; $i++)
        {
            $str .= mt_rand(0, 9);
        }

        $time = time() + 8 * 3600;

        return $time . $str;
    }

    /**
     *  返回一个生成的不重复文件
     * 
     * @param type $dir
     * @param type $filetype
     * @return string
     */
    function unique_name($dir, $filetype = '')
    {
        $filename = '';
        while (empty($filename))
        {

            $filename = self::random_filename() . $filetype;

            if (file_exists($dir . $filename))
            {
                $filename = '';
            }
        }

        return $filename;
    }

    /**
     *  返回文件后缀名
     *
     * @access  public
     * @param
     *
     * @return  string      文件后缀名
     */
    public static function get_filetype($path)
    {
        $pos = strrpos($path, '.');
        if ($pos !== false)
        {
            return substr($path, $pos);
        }
        else
        {
            return '';
        }
    }

    /**
     *  得到文件的mime
     * @param type $file
     * @return string
     */
    public static function get_mime($file)
    {
        $ext = strtolower(trim(substr(strrchr($file, '.'), 1, 10)));
        if ($ext == '')
            return '';
        $mime_types = array(
            'acx' => 'application/internet-property-stream',
            'ai' => 'application/postscript',
            'aif' => 'audio/x-aiff',
            'aifc' => 'audio/x-aiff',
            'aiff' => 'audio/x-aiff',
            'asp' => 'text/plain',
            'aspx' => 'text/plain',
            'asf' => 'video/x-ms-asf',
            'asr' => 'video/x-ms-asf',
            'asx' => 'video/x-ms-asf',
            'au' => 'audio/basic',
            'avi' => 'video/x-msvideo',
            'axs' => 'application/olescript',
            'bas' => 'text/plain',
            'bcpio' => 'application/x-bcpio',
            'bin' => 'application/octet-stream',
            'bmp' => 'image/bmp',
            'c' => 'text/plain',
            'cat' => 'application/vnd.ms-pkiseccat',
            'cdf' => 'application/x-cdf',
            'cer' => 'application/x-x509-ca-cert',
            'class' => 'application/octet-stream',
            'clp' => 'application/x-msclip',
            'cmx' => 'image/x-cmx',
            'cod' => 'image/cis-cod',
            'cpio' => 'application/x-cpio',
            'crd' => 'application/x-mscardfile',
            'crl' => 'application/pkix-crl',
            'crt' => 'application/x-x509-ca-cert',
            'csh' => 'application/x-csh',
            'css' => 'text/css',
            'dcr' => 'application/x-director',
            'der' => 'application/x-x509-ca-cert',
            'dir' => 'application/x-director',
            'dll' => 'application/x-msdownload',
            'dms' => 'application/octet-stream',
            'doc' => 'application/msword',
            'dot' => 'application/msword',
            'dvi' => 'application/x-dvi',
            'dxr' => 'application/x-director',
            'eps' => 'application/postscript',
            'etx' => 'text/x-setext',
            'evy' => 'application/envoy',
            'exe' => 'application/octet-stream',
            'fif' => 'application/fractals',
            'flr' => 'x-world/x-vrml',
            'flv' => 'video/x-flv',
            'gif' => 'image/gif',
            'gtar' => 'application/x-gtar',
            'gz' => 'application/x-gzip',
            'h' => 'text/plain',
            'hdf' => 'application/x-hdf',
            'hlp' => 'application/winhlp',
            'hqx' => 'application/mac-binhex40',
            'hta' => 'application/hta',
            'htc' => 'text/x-component',
            'htm' => 'text/html',
            'html' => 'text/html',
            'htt' => 'text/webviewhtml',
            'ico' => 'image/x-icon',
            'ief' => 'image/ief',
            'iii' => 'application/x-iphone',
            'ins' => 'application/x-internet-signup',
            'isp' => 'application/x-internet-signup',
            'jfif' => 'image/pipeg',
            'jpe' => 'image/jpeg',
            'jpeg' => 'image/jpeg',
            'jpg' => 'image/jpeg',
            'js' => 'application/x-javascript',
            'latex' => 'application/x-latex',
            'lha' => 'application/octet-stream',
            'lsf' => 'video/x-la-asf',
            'lsx' => 'video/x-la-asf',
            'lzh' => 'application/octet-stream',
            'm13' => 'application/x-msmediaview',
            'm14' => 'application/x-msmediaview',
            'm3u' => 'audio/x-mpegurl',
            'man' => 'application/x-troff-man',
            'mdb' => 'application/x-msaccess',
            'me' => 'application/x-troff-me',
            'mht' => 'message/rfc822',
            'mhtml' => 'message/rfc822',
            'mid' => 'audio/mid',
            'mny' => 'application/x-msmoney',
            'mov' => 'video/quicktime',
            'movie' => 'video/x-sgi-movie',
            'mp2' => 'video/mpeg',
            'mp3' => 'audio/mpeg',
            'mpa' => 'video/mpeg',
            'mpe' => 'video/mpeg',
            'mpeg' => 'video/mpeg',
            'mpg' => 'video/mpeg',
            'mpp' => 'application/vnd.ms-project',
            'mpv2' => 'video/mpeg',
            'ms' => 'application/x-troff-ms',
            'mvb' => 'application/x-msmediaview',
            'nws' => 'message/rfc822',
            'oda' => 'application/oda',
            'p10' => 'application/pkcs10',
            'p12' => 'application/x-pkcs12',
            'p7b' => 'application/x-pkcs7-certificates',
            'p7c' => 'application/x-pkcs7-mime',
            'p7m' => 'application/x-pkcs7-mime',
            'p7r' => 'application/x-pkcs7-certreqresp',
            'p7s' => 'application/x-pkcs7-signature',
            'pbm' => 'image/x-portable-bitmap',
            'pdf' => 'application/pdf',
            'pfx' => 'application/x-pkcs12',
            'pgm' => 'image/x-portable-graymap',
            'php' => 'text/plain',
            'pko' => 'application/ynd.ms-pkipko',
            'pma' => 'application/x-perfmon',
            'pmc' => 'application/x-perfmon',
            'pml' => 'application/x-perfmon',
            'pmr' => 'application/x-perfmon',
            'pmw' => 'application/x-perfmon',
            'png' => 'image/png',
            'pnm' => 'image/x-portable-anymap',
            'pot,' => 'application/vnd.ms-powerpoint',
            'ppm' => 'image/x-portable-pixmap',
            'pps' => 'application/vnd.ms-powerpoint',
            'ppt' => 'application/vnd.ms-powerpoint',
            'prf' => 'application/pics-rules',
            'ps' => 'application/postscript',
            'pub' => 'application/x-mspublisher',
            'qt' => 'video/quicktime',
            'ra' => 'audio/x-pn-realaudio',
            'ram' => 'audio/x-pn-realaudio',
            'ras' => 'image/x-cmu-raster',
            'rgb' => 'image/x-rgb',
            'rmi' => 'audio/mid',
            'roff' => 'application/x-troff',
            'rtf' => 'application/rtf',
            'rtx' => 'text/richtext',
            'scd' => 'application/x-msschedule',
            'sct' => 'text/scriptlet',
            'setpay' => 'application/set-payment-initiation',
            'setreg' => 'application/set-registration-initiation',
            'sh' => 'application/x-sh',
            'shar' => 'application/x-shar',
            'sit' => 'application/x-stuffit',
            'snd' => 'audio/basic',
            'spc' => 'application/x-pkcs7-certificates',
            'spl' => 'application/futuresplash',
            'src' => 'application/x-wais-source',
            'sst' => 'application/vnd.ms-pkicertstore',
            'stl' => 'application/vnd.ms-pkistl',
            'stm' => 'text/html',
            'svg' => 'image/svg+xml',
            'sv4cpio' => 'application/x-sv4cpio',
            'sv4crc' => 'application/x-sv4crc',
            'swf' => 'application/x-shockwave-flash',
            't' => 'application/x-troff',
            'tar' => 'application/x-tar',
            'tcl' => 'application/x-tcl',
            'tex' => 'application/x-tex',
            'texi' => 'application/x-texinfo',
            'texinfo' => 'application/x-texinfo',
            'tgz' => 'application/x-compressed',
            'tif' => 'image/tiff',
            'tiff' => 'image/tiff',
            'tr' => 'application/x-troff',
            'trm' => 'application/x-msterminal',
            'tsv' => 'text/tab-separated-values',
            'txt' => 'text/plain',
            'uls' => 'text/iuls',
            'ustar' => 'application/x-ustar',
            'vcf' => 'text/x-vcard',
            'vrml' => 'x-world/x-vrml',
            'wav' => 'audio/x-wav',
            'wcm' => 'application/vnd.ms-works',
            'wdb' => 'application/vnd.ms-works',
            'wks' => 'application/vnd.ms-works',
            'wmf' => 'application/x-msmetafile',
            'wmv' => 'video/x-ms-wmv',
            'wps' => 'application/vnd.ms-works',
            'wri' => 'application/x-mswrite',
            'wrl' => 'x-world/x-vrml',
            'wrz' => 'x-world/x-vrml',
            'xaf' => 'x-world/x-vrml',
            'xbm' => 'image/x-xbitmap',
            'xla' => 'application/vnd.ms-excel',
            'xlc' => 'application/vnd.ms-excel',
            'xlm' => 'application/vnd.ms-excel',
            'xls' => 'application/vnd.ms-excel',
            'xlt' => 'application/vnd.ms-excel',
            'xlw' => 'application/vnd.ms-excel',
            'xof' => 'x-world/x-vrml',
            'xpm' => 'image/x-xpixmap',
            'xwd' => 'image/x-xwindowdump',
            'z' => 'application/x-compress',
            'zip' => 'application/zip',
        );
        return isset($mime_types[$ext]) ? $mime_types[$ext] : '';
    }

    public static function init_swfupload($user_id, $folder_id, $allow_type, $allow_type_post)
    {
        $init = 'var swfu = \'\';
            	window.onload = function() {
		swfu = new SWFUpload({
			flash_url:"media/js/swfupload/swfupload.swf",
                        flash9_url : "media/js/swfupload/swfupload_fp9.swf",
			upload_url:"upload.php?dosubmit=1",
			file_post_name : "Filedata",
			post_params:{"SWFUPLOADSESSID":"' . session_id() . '","allow_type_post":"' . $allow_type_post . '","user_id":"' . $user_id . '","folder_id":"' . $folder_id . '","dosubmit":"1"},
			file_size_limit:"100 MB",
			file_types:"' . $allow_type . '",
			file_types_description:"All Files",
			file_upload_limit:"10",
			custom_settings : {
			progressTarget : "fsUploadProgress",
			cancelButtonId : "btnCancel",
                        upload_successful : false
		},
		debug: false,
	 
		button_image_url : "media/js/swfupload/XPButtonUploadText_61x22.png",
		button_placeholder_id : "spanButtonPlaceholder",
		button_width: 61,
		button_height: 22,

		swfupload_preload_handler : swfUploadPreLoad,
		swfupload_load_failed_handler : swfUploadLoadFailed,
		swfupload_loaded_handler : swfUploadLoaded,
		file_queued_handler : fileQueued,
		file_queue_error_handler : fileQueueError,
		file_dialog_complete_handler : fileDialogComplete,
		upload_start_handler : uploadStart,
		upload_progress_handler : uploadProgress,
		upload_error_handler : uploadError,
		upload_success_handler : uploadSuccess,
		upload_complete_handler : uploadComplete,
		queue_complete_handler : queueComplete	
			
		})
                
              }';
        return $init;
    }

    public static function create_time_path()
    {
        return date('Y') . DIRECTORY_SEPARATOR . date('m') . DIRECTORY_SEPARATOR . date('d') . DIRECTORY_SEPARATOR;
    }

}